package com.njxxted.activiti.common.config;

import com.google.common.collect.Lists;
import com.njxxted.activiti.common.intercept.SysInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述：解决请求跨域问题
 * <p>
 * 作者：HuTongFu
 * 时间：2019/6/25 10:26
 */
@Configuration
public class SysWebServerConfig implements WebMvcConfigurer {

    @Autowired
    SysInterceptor sysInterceptor;

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        /*是否允许请求带有验证信息*/
        corsConfiguration.setAllowCredentials(true);
        /*允许访问的客户端域名*/
        corsConfiguration.addAllowedOrigin("*");
        /*允许服务端访问的客户端请求头*/
        corsConfiguration.addAllowedHeader("*");
        /*允许访问的方法名,GET POST等*/
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

    //资源映射路径
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    }

    /**
     * 配置自定义拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //过滤出不需要拦截的URI
        List<String> patterns = Lists.newArrayList();
        patterns.add("/error");
        patterns.add("/base/login");
        patterns.add("/base/logout");
        patterns.add("/swagger-ui.html");
        patterns.add("/swagger-resources");
        patterns.add("/swagger-resources/**");
        patterns.add("/**/webjars/**");
        patterns.add("/service/**");
        patterns.add("/**/image/**");
        patterns.add("/act/rest/task/attachment/**");
        patterns.add("/act/rest/task/down/**");
        patterns.add("/base/showHead/**");
        registry.addInterceptor(sysInterceptor).addPathPatterns("/**").excludePathPatterns(patterns);
    }

}
